/**
 * 封装UEditor
 */
import React from 'react';
import { Row, Col, Tabs, Avatar } from 'antd';
const TabPane = Tabs.TabPane;
import axios from 'axios';
import $ from 'jquery'
// import './index.less';
import config from '../../config/config';

// 引入Cookie
import Cookie from 'js-cookie'

import styles from './Editor.less'
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);

class UEditor extends React.Component {
    constructor(props, context) {
        super(props, context);
        // this.editor = {};
        this.editItem = null;
        this.id = '';
        this.state = {
            editable: (props.editable === false ? false : true),
            html: props.html,
            tabList: [
                { tabName: '5.5寸以上', claBox: 'Xphone_box', phone: 'phone1' },
                { tabName: '5.5寸屏', claBox: 'Bphone_box', phone: 'phone2' },
                { tabName: '5寸及以下', claBox: 'Mphone_box', phone: 'phone3' }]
        };

    }
    //完成：正在被重新渲染，状态已变化
    componentDidUpdate(prevProps, prevState) {
        if (this.state.editable) {
            this.updateUeditor();
        }
        var me = this;
        if (!(!!window.ActiveXObject || "ActiveXObject" in window)) {//如果不是IE浏览器
            $(".phone_content").each(function () {//使外部样式失效，达到屏蔽效果
                if (this.shadowRoot) {
                    this.shadowRoot.innerHTML = "<style>img{height:auto!important;} *{max-width:100%!important;}</style>" + me.state.html
                } else {
                    this.attachShadow({ mode: 'open' });
                    this.shadowRoot.innerHTML = "<style>img{height:auto!important;} *{max-width:100%!important;}</style>" + me.state.html
                }
            })
        }
    }
    updateUeditor() {
        let props = this.props
        let me = this
        if (!this.editItem && this.state.editable) {
            this.initEditor(props)//使用配置项初始化UEDITOR,并监听各种事件
            this.editItem.addListener("ready", function () {
                if (me.state.html !== '') {
                    me.editItem.setContent(me.state.html)
                }
            });
        }
    }

    componentWillReceiveProps(nextProps) {
        // console.log(this.editItem&&this.editItem.getContent())
        // if(this.editItem &&(this.editItem.getContent() !== nextProps.html)){
        //     // this.editItem.setContent(nextProps.html)
        // }
        this.setState({ html: nextProps.html, editable: (nextProps.editable === false ? false : true) })
    }
    componentDidMount() {
        var me = this;
        if (!(!!window.ActiveXObject || "ActiveXObject" in window)) {//如果不是IE浏览器
            $(".phone_content").each(function () {//使外部样式失效，达到屏蔽效果
                this.attachShadow({ mode: 'open' });
                this.shadowRoot.innerHTML = "<style>img{height:auto!important;} *{max-width:100%!important;}</style>" + me.props.html
            })
        }
        if (this.state.editable) {
            this.updateUeditor();
        }
    }
    componentWillUnmount() {
        UE.delEditor(this.props.id);
    }
    //自定义上传
    customUploadImg(props) {
    }
    //组件初始化
    initEditor(props) {
        //配置ueditor.config
        // console.log(props)
        var customConfig = {
            elementPathEnabled: false,
            serverUrl: config.baseUrl + `admin/oss/ueditor/singleUpload`,
            catchRemoteImageEnable: true,
            autoClearinitialContent: true,
        }
        UE.Editor.prototype.placeholder = function (justPlainText) {
            var _editor = this;
            _editor.addListener("focus", function () {
                var localHtml = _editor.getPlainTxt();
                if (localHtml.trim() === justPlainText.trim()) {
                    _editor.setContent("");
                }
            });
            _editor.addListener("blur", function () {
                var localHtml = _editor.getContent();
                if (!localHtml) {
                    _editor.setContent('<p></p><p></p><p></p><p style="text-align: center;"><span style="font-size: 24px; color: rgb(191, 191, 191);">' + justPlainText + '</span></p>');
                }
            });
            _editor.ready(function () {
                _editor.fireEvent("blur");
            });
            _editor.addListener('selectionchange', function (type) {
                var localHtml = _editor.getPlainTxt();
                if (localHtml.trim() === justPlainText.trim()) {
                    me.props.inputChange("");
                } else {
                    me.props.inputChange(this.getContent());
                }
            });
        };

        this.editItem = UE.getEditor(props.id, { ...customConfig });
        this.editItem.placeholder("试试直接把编辑好的图文样式复制粘贴到这儿，有惊喜哦~");
        // this.editItem.ready((ueditor) => {
        //     this.editItem.setContent(this.props.html)
        //     // console.log(ueEditor)
        //     if (!ueditor) {
        //         UE.delEditor(props.id);
        //         self.initEditor();
        //     }
        // });
        let me = this;
    }

    render() {
        let { editable, html, tabList } = this.state
        let customStyle = this.props.style || { width: '100%', height: 400 }
        let that = this;

        function changePhone(e) {
            var that = e.currentTarget;
            var pageY = e.clientY;
            //鼠标按下获取当前容器div的top值
            var oldHeight = parseInt(that.scrollTop);

            document.onmousemove = function (event) {
                var e = event || window.event;
                var height = -(e.clientY - pageY) + oldHeight;
                that.scrollTop = height;
            }
        }
        document.onmouseup = function (e) {
            document.onmousemove = null;
        };
        if (editable) {
            return (
                <div style={customStyle} className={cx('block')}>
                    <Row>
                        <Col span={14}>
                            <div className={cx('editor_box')}>
                                <script id={this.props.id} name="myContent" type="text/plain"></script>
                            </div>
                        </Col>
                        <Col span={1}></Col>
                        <Col span={9}>
                            <Tabs tabPosition={'top'} style={{ width: '100%' }} animated={false}>

                                {tabList.map((item, index) => {
                                    return (
                                        <TabPane tab={item.tabName} key={index} forceRender={true}>
                                            <div className={cx('phone_box', `${item.claBox}`)}>
                                                <div className={cx('top_box', `${item.phone}`)} onMouseDown={(e) => { changePhone(e) }} >
                                                    <div className={cx('mask')}></div>
                                                    <div className={cx('title')}>{this.props.title}</div>
                                                    {this.props.startDate !== '' && this.props.endDate !== '' &&
                                                        <div className={cx('time')}>活动时间：{this.props.startDate}-{this.props.endDate}</div>
                                                    }
                                                    <div className={'phone_content'} dangerouslySetInnerHTML={{ __html: html }}></div>
                                                </div>
                                            </div>
                                        </TabPane>
                                    )
                                })}
                            </Tabs>
                        </Col>
                    </Row>
                </div>
            )
        } else {
            return (
                <div style={customStyle}>
                    <Row>
                        <Col span={12}>
                            <Tabs tabPosition={'top'} style={{ width: '100%' }} animated={false} >
                                {tabList.map((item, index) => {
                                    return (
                                        <TabPane tab={item.tabName} key={index} forceRender={true}>
                                            <div className={cx('phone_box', `${item.claBox}`)}>
                                                <div className={cx('top_box', `${item.phone}`)} onMouseDown={(e) => { changePhone(e) }} >
                                                    <div className={cx('mask')}></div>
                                                    <div className={cx('title')}>{this.props.title}</div>
                                                    {this.props.startDate !== '' && this.props.endDate !== '' &&
                                                        <div className={cx('time')}>活动时间：{this.props.startDate}-{this.props.endDate}</div>
                                                    }
                                                    <div className={'phone_content'} dangerouslySetInnerHTML={{ __html: html }}></div>
                                                </div>
                                            </div>
                                        </TabPane>
                                    )
                                })}
                            </Tabs>
                        </Col>
                    </Row>
                </div>
            )
        }
    }
}
export default UEditor;
